/*
 *  Copyright (C) <2009>  Pavel Vakeš <pavel.vakes@gmail.com>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef MailChecker_HEADER
#define MailChecker_HEADER

#include <QObject>
#include <QBasicTimer>
#include <QTimerEvent>
#include <QSslSocket>
#include <QSslCertificate>
#include <QSslKey>
#include <QFile>
#include <QList>

#include <KProcess>

#include "account.h"
#include "certificate_details_dialog.h"

class MailChecker : public QObject
{
	Q_OBJECT

	public:
		enum Action {
			OPEN_CONNECTION, VERIFY_CERT, VERIFY_USER, VERIFY_PASS, GET_STAT, CLOSE_CONNECTION
		};

		MailChecker(Account * account);
		~MailChecker();

		void startPeriodicallyCheck();
		void stopCheck();

		QString accountName();
		int timeToCheck();

		int messages();
		QString checkError();

	public slots:
		void startCheck();
		void runMailClient();

		void acceptCertificate();
		void rejectCertificate();

	protected:
		void timerEvent(QTimerEvent *event);

	private:
		void writeData(Action action);

		void endCheck(const QString error = QString::null);

		Account *account;
		QBasicTimer check_timer;
		QBasicTimer connection_timer;
		QSslSocket socket;
		Action actual_action;
		QByteArray read_data;

		CertificateDetailsDialog *certificate_details_dialog;

		int time_to_check;
		int check_messages;
		QString check_error;

	private slots:
		void socketStateChanged(QAbstractSocket::SocketState socketState);
		void socketError(QAbstractSocket::SocketError socketError);
		void readData();

		void showCertificateDetailsDialog(const QSslCertificate &certificate);
		void closeCertificateDetailsDialog();

	signals:
		void actionChanged(MailChecker::Action action);
		void endCheckMessages(int count);
		void endCheckError(QString error);
		void timeToCheckChanged(int time_to_check);

		void certificateAccepted(Account *);
};

#endif
